﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ECI.Entities;
using ECI.BaseLanguage;
using ECI.CommonLibrary;
using ECI.CoreLibrary;

namespace ECI.DynamicData
{
    public class QuerySqlCreate
    {
        private static ECI.CoreLibrary.CommonLibrary cmn = new ECI.CoreLibrary.CommonLibrary();

        public static string GetQuerySQLByField(EciTable table)
        {
            if (table.PrimaryKey == null) throw new Exception(Lang.A00058.Read() + "【" + table.Code + "】" + Lang.A00226.Read());//当前程序【" + table.Code + "】没有配置主键
            string sql = "SELECT A." + table.PrimaryKey.Name + " AS KEY_0, {#CONTENT#} FROM " + table.Fname + " A  WHERE 1=1";

            if (table.IsMultiCompany.ToMyString() == "1") sql += " AND COMPANY_CODE=" + cmn.SQLQ(UserInfo.CompanyCode); //多公司支持的情况

            if (!string.IsNullOrEmpty(table.DefaultCondition)) sql += " AND " + table.DefaultCondition; //默认查询条件

            if (!string.IsNullOrEmpty(table.Condition))  //级联查询条件
            {
                string condition = PageHelper.Request(table.Condition);
                //if (condition == "") throw new Exception("程序【" + table.Code + "】配置了级联条件" + table.Condition + "但是当前没有传入该值");
                if (condition == "") throw new Exception(Lang.A00059.Read() + "【" + table.Code + "】" + Lang.A00062.Read() + table.Condition + Lang.A00060.Read());
                sql += " AND " + table.Condition + "=" + cmn.SQLQ(condition);
            }

            string query = "";

            foreach (EciField field in table.ListShow)
            {
                //2010-07-14 查询显示GRID数据的时候增加对ShowConvert的判断
                if (field.ShowConvert.Length > 0)
                {
                    query += "," + field.ShowConvert + " AS " + field.Name;
                    continue;
                }

                if (string.IsNullOrEmpty(field.JoinTable))
                {
                    #region 不是外接表的情况下


                    //下拉框 字典配置不为空的情况 采用DECODE方式做代码转换
                    if (!string.IsNullOrEmpty(field.DropdownlistConfig))
                    {
                        #region 固定格式下拉列表框
                        string[] array = field.DropdownlistConfig.Split(',');

                        string str = ",DECODE(A." + field.DbField + "{0}) " + field.Name;
                        string decodeContent = "";

                        foreach (string item in array)
                        {
                            string[] itemArray = item.Split('|');
                            string code = itemArray[0].Trim();
                            string name = "";
                            if (itemArray.Length == 1)
                            {
                                name = code;
                            }
                            else
                            {
                                name = itemArray[1].Trim();
                            }

                            decodeContent += "," + cmn.SQLQ(code) + "," + cmn.SQLQ(name);
                        }

                        str = string.Format(str, decodeContent);
                        query += str;
                        #endregion
                    }
                    else
                    {

                        if ((field.DictionaryType == "DROPDOWNLIST" || field.DictionaryType == "CHOOSE") && field.DictionaryTypeConfig != "")
                        {

                            // 判断是否配置了代码转换函数 如果有 则用函数，如果没有则用放大镜配置的代码转换
                            //2010-06-21 新增加
                            if (field.ShowConvert.Length > 0)
                            {
                                string showConvert = field.ShowConvert;
                                query += "," + showConvert + " AS " + field.Name;
                            }
                            else
                            {
                                #region 放大镜配置 或者 预定义 下拉列表框
                                //一种错误的思想被批判：
                                //既然 选择配置中有配置  下拉框 或者 放大镜，那么 基础配置程序为什么还要配置，是否根据此来自动
                                //结论：不可

                                //给出给出具体的配置错误提示信息  如果CHOOSE  必须设置 DictionaryTypeConfig

                                EciDataHelp eciDataHelp = new EciDataHelp(EciDataHelpEnum.QueryType);
                                eciDataHelp.QueryType = field.DictionaryTypeConfig;
                                eciDataHelp = eciDataHelp.FetchEntity();
                                if (eciDataHelp.NotFetchData) throw new Exception(Lang.A00061.Read() + ":" + field.DictionaryTypeConfig);//配置错误:DATA_HELP中不存在类型

                                string joinShowField = eciDataHelp.DataChangeName;
                                string joinTable = eciDataHelp.DataSource;//取消  2010-02-09
                                string dataSource = eciDataHelp.ConvertSql;
                                string joinTableField = eciDataHelp.DataChangeCode;

                                string param = eciDataHelp.Param;
                                //处理运行时参数
                                if (param.Length > 0)
                                {
                                    string[] array = param.Split(',');
                                    foreach (string section in array)
                                    {
                                        if (section.Trim().Length > 0)
                                        {
                                            dataSource = dataSource.Replace("'{" + section + "}'", "A." + section);
                                        }
                                    }
                                }

                                //query += ",( SELECT B." + joinShowField + "  FROM  ( " + dataSource + "  ) B WHERE  ROWNUM=1 AND B." + joinTableField + "=A." + field.DbField + " AND ROWNUM=1) AS " + field.Name;
                                query += ",F_NAME(A." + field.Name + ",'" + field.DictionaryTypeConfig + "') AS " + field.Name;
                                #endregion
                            }
                        }
                        else if (field.DictionaryType == "CHECK")
                        {
                            query += ",DECODE(A." + field.Name + ",'Y','是','否') " + field.Name;
                        }
                        else if (field.DictionaryType == "RADIONGROUP")
                        {
                            string[] array = field.DictionaryTypeConfig.Split(',');
                            string str = ",DECODE(A." + field.DbField + "{0}) " + field.Name;
                            string decodeContent = "";

                            foreach (string item in array)
                            {
                                string[] itemArray = item.Split('|');
                                string code = itemArray[0].Trim();
                                string name = "";
                                if (itemArray.Length == 1)
                                {
                                    name = code;
                                }
                                else
                                {
                                    name = itemArray[1].Trim();
                                }

                                decodeContent += "," + cmn.SQLQ(code) + "," + cmn.SQLQ(name);
                            }

                            str = string.Format(str, decodeContent);
                            query += str;
                        }
                        else
                        {
                            //正常的字段查询
                            //针对数据库类型是日期类型增加 数据格式

                            if (field.PhysicalType == "DATE")
                            {
                                string dataFormat = "";
                                if (field.DataFormatGrid.Trim().Length > 0) dataFormat = field.DataFormatGrid;
                                query += "," + DBUtility.Instance.SqlQToChar(field.DbField, dataFormat) + " AS " + field.Name;
                            }
                            else
                            {
                                query += "," + "A." + field.DbField;
                                if (field.DbField != field.Name) query += " AS " + field.Name;
                            }
                        }
                    }

                    #endregion
                }
                else
                {
                    #region 外接表的情况下
                    query += ",( SELECT B." + field.JoinShowField + "  FROM  " + field.JoinTable + " B WHERE B." + field.JoinTableField + "=A." + field.Name + GetJoinCondition(field) + " AND ROWNUM=1) AS " + field.Name;
                    #endregion
                }
            }

            if (query.Length > 0) query = query.Substring(1);
            if (query == "") query = "1";
            sql = sql.Replace("{#CONTENT#}", query);//2010-11-24修改

            sql = SQLParamConvert.Convert(sql);//转化SQL参数替换

            return sql;
        }


        private static string GetJoinCondition(EciField field)
        {
            if (string.IsNullOrEmpty(field.JoinCondition))
            {
                return "";
            }
            else
            {
                return " AND " + field.JoinCondition;
            }
        }
    }
}
